<template>
  <div class="app-container">
    <!-- 导航 -->
    <NavBarBread :bread="[$route.meta.parentName, $route.meta.menuName]">
      <el-tooltip class="item" effect="dark" content="导出" placement="top-end">
        <i
          class="el-icon-sold-out"
          style="font-size: 20px; color: #05a7ab"
          @click="handelExport"
        />
      </el-tooltip>
    </NavBarBread>
    <!-- 查询条件 -->
    <div class="serach-container">
      <div class="search-inputs">
        <el-form
          :inline="true"
          :model="simpleForm"
          class="demo-form-inline"
          label-position="right"
          label-width="100px"
        >
          <el-form-item label="VIN">
            <el-input
              v-model="simpleForm.vin"
              maxlength="17"
              placeholder="请输入VIN码"
            />
          </el-form-item>
          <el-form-item label="大区">
            <el-select
              v-model="simpleForm.saleRegionName"
              clearable
              placeholder="请选择大区"
              @change="
                $forceUpdate(),
                  (simpleForm.provinceCode = ''),
                  (complexForm.cityCode = '')
              "
            >
              <el-option
                v-for="(item, index) in regions"
                :key="index + '_' + item.bigAreaCode"
                :label="item.bigAreaName"
                :value="item.bigAreaCode"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="省份">
            <el-select
              v-model="simpleForm.provinceCode"
              filterable
              clearable
              placeholder="请选择省份"
              @change="$forceUpdate(), (complexForm.cityCode = '')"
            >
              <el-option
                v-for="(item, index) in provinceOptions"
                :key="index + '_' + item.provinceCode"
                :label="item.provinceName"
                :value="item.provinceCode"
              />
            </el-select>
          </el-form-item>
          <el-button type="primary" @click="queryList">查询</el-button>
          <el-button @click="handelRest">重置</el-button>
        </el-form>
        <div v-show="isMore">
          <el-form
            :inline="true"
            :model="complexForm"
            class="demo-form-inline"
            label-position="right"
            label-width="100px"
          >
            <el-form-item label="城市">
              <el-select
                v-model="complexForm.cityCode"
                filterable
                clearable
                placeholder="请选择城市"
                @change="$forceUpdate()"
              >
                <el-option
                  v-for="(item, index) in cityOptions"
                  :key="index + '_' + item.cityCode"
                  :label="item.cityName"
                  :value="item.cityCode"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="店简称">
              <el-input
                v-model="complexForm.dealerShortName"
                placeholder="请输入店简称"
              />
            </el-form-item>
            <el-form-item label="店代码">
              <el-input
                v-model="complexForm.dealerCode"
                placeholder="请输入店代码"
              />
            </el-form-item>
            <el-form-item label="车系标准名称">
              <el-select
                v-model="complexForm.seriesNormalName"
                filterable
                clearable
                placeholder="请选择车系标准名称"
                @change="(complexForm.modelName = ''), $forceUpdate()"
              >
                <el-option
                  v-for="item in vehicleNormalOptions"
                  :key="item.seriesNormalName"
                  :label="item.seriesNormalName"
                  :value="item.seriesNormalName"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="车系">
              <el-select
                v-model="complexForm.seriesName"
                filterable
                clearable
                placeholder="请选择车系"
                @change="(complexForm.modelName = ''), $forceUpdate()"
              >
                <el-option
                  v-for="item in vehicleOptions"
                  :key="item.seriesName"
                  :label="item.seriesName"
                  :value="item.seriesName"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="车型">
              <el-select
                v-model="complexForm.modelName"
                filterable
                clearable
                placeholder="请选择车型"
                @change="$forceUpdate()"
              >
                <el-option
                  v-for="item in modelOptios"
                  :key="item.modelName"
                  :label="item.modelName"
                  :value="item.modelName"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="上牌大区">
              <el-select
                v-model="complexForm.plateBigArea"
                clearable
                placeholder="请选择上牌大区"
                @change="(complexForm.plateCity = ''), $forceUpdate()"
              >
                <el-option
                  v-for="item in plateRegions"
                  :key="item.bigAreaCode"
                  :label="item.bigAreaName"
                  :value="item.bigAreaCode"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="上牌城市">
              <el-select
                v-model="complexForm.plateCity"
                filterable
                clearable
                placeholder="请选择上牌城市"
                @change="$forceUpdate()"
              >
                <el-option
                  v-for="item in plateCityOptions"
                  :key="item.cityCode"
                  :label="item.cityName"
                  :value="item.cityCode"
                />
              </el-select>
            </el-form-item>
          </el-form>
          <el-form
            :inline="true"
            class="demo-form-inline"
            label-position="right"
            label-width="100px"
          >
            <el-form-item label="开票日期">
              <el-date-picker
                v-model="invoiceDate"
                type="daterange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
              />
            </el-form-item>
            <el-form-item label="上牌日期">
              <el-date-picker
                v-model="plateDate"
                type="daterange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
              />
            </el-form-item>
          </el-form>
        </div>
      </div>
      <div class="search-toggle">
        <el-button type="text" @click="handelToggle">
          {{ isMore ? "普通搜索" : "高级搜索" }}
        </el-button>
      </div>
    </div>
    <!-- 数据内容 -->
    <div class="section-container">
      <el-table
        v-loading="listLoading"
        size="mini"
        :data="tables.data"
        border
        fit
        highlight-current-row
        style="width: 100%"
        height="600"
      >
        <el-table-column type="index" label="序号" width="50" align="center" />
        <el-table-column
          v-for="item in tables.columns"
          :key="item.key"
          :width="item.width"
          :label="item.lable"
          :align="item.align"
          :show-overflow-tooltip="true"
          header-align="center"
        >
          <template slot-scope="{ row }">
            <span v-if="item.key === 'dealerType'">{{
              row[item.key] | dealerTypeFilter
            }}</span>
            <span v-else-if="item.key === 'buyType'">{{
              row[item.key] | buyTypeFilter
            }}</span>
            <span v-else-if="item.key === 'localInvoicing'">{{
              row[item.key] | localInvoicingFilter
            }}</span>
            <span v-else-if="item.key === 'stockInStatus'">{{
              row[item.key] | stockInStatusFilter
            }}</span>
            <span v-else-if="item.key === 'stockOutStatus'">{{
              row[item.key] | stockOutStatusFilter
            }}</span>
            <span v-else-if="item.key === 'useType'">{{
              row[item.key] | useTypeFilter
            }}</span>
            <span v-else>{{ row[item.key] }}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="操作" width="100" fixed="right">
          <template slot-scope="{ row }">
            <el-button type="text" size="small" @click="handelCheckDetail(row)">
              详情
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <pagination
        :total="total"
        :page.sync="pages.pageNum"
        :limit.sync="pages.pageSize"
        @pagination="changePages"
      />
    </div>
    <!-- 详情弹窗 -->
    <el-dialog title="详情" :visible.sync="detailVisible" width="60%">
      <div class="detailContainer">
        <div v-for="item in tables.columns" :key="item.key" class="detailItem">
          <div v-if="item.key === 'dealerType'">
            <span class="detailTitle">{{ item.lable }}：</span>
            <span>{{ dealerTypeMap[detailData[item.key]] }}</span>
          </div>
          <div v-else-if="item.key === 'buyType'">
            <span class="detailTitle">{{ item.lable }}：</span>
            <span>{{ buyTypeMap[detailData[item.key]] }}</span>
          </div>
          <div v-else-if="item.key === 'localInvoicing'">
            <span class="detailTitle">{{ item.lable }}：</span>
            <span>{{ localInvoicingMap[detailData[item.key]] }}</span>
          </div>
          <div v-else-if="item.key === 'stockInStatus'">
            <span class="detailTitle">{{ item.lable }}：</span>
            <span>{{ stockInStatusMap[detailData[item.key]] }}</span>
          </div>
          <div v-else-if="item.key === 'stockOutStatus'">
            <span class="detailTitle">{{ item.lable }}：</span>
            <span>{{ stockOutStatusMap[detailData[item.key]] }}</span>
          </div>
          <div v-else-if="item.key === 'useType'">
            <span class="detailTitle">{{ item.lable }}：</span>
            <span>{{ useTypeMap[detailData[item.key]] }}</span>
          </div>
          <div v-else>
            <span class="detailTitle">{{ item.lable }}：</span>
            <span>{{ detailData[item.key] }}</span>
          </div>
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="detailVisible = false"
          >确 定</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { queryList, fenceVehicleExport } from "@/api/crossRegionalMonitoring";
import Pagination from "@/components/Pagination";
import NavBarBread from "@/components/NavBarBread";
import {
  exportExcelByBlob,
  getStorageByKey,
  unique_arr_by_key,
} from "@/utils/public";
import {
  dateFtt,
  dealerTypeMap,
  buyTypeMap,
  localInvoicingMap,
  stockInStatusMap,
  stockOutStatusMap,
  useTypeMap,
} from "@/utils/public";
export default {
  name: "MonitoringVehicle",
  components: { Pagination, NavBarBread },
  filters: {
    // 4S店类型
    dealerTypeFilter(status) {
      return dealerTypeMap[status];
    },
    // 购车领域
    buyTypeFilter(status) {
      return buyTypeMap[status];
    },
    // 是否本店开票0=异地 1=本地 , localInvoicing
    localInvoicingFilter(status) {
      return localInvoicingMap[status];
    },
    // stockInStatus (integer, optional): 入库状态，0=采购入库，1=调拨入库，2=退车入库 ,
    stockInStatusFilter(status) {
      return stockInStatusMap[status];
    },
    // stockOutStatus (integer, optional): 出库状态，0=销售出库，1=调拨出库，2=退车出库 ,
    stockOutStatusFilter(status) {
      return stockOutStatusMap[status];
    },
    // useType (integer, optional): 使用性质，0=营运，1=非营运，2=出租客运 ,
    useTypeFilter(status) {
      return useTypeMap[status];
    },
  },
  data() {
    return {
      dealerTypeMap,
      buyTypeMap,
      localInvoicingMap,
      stockInStatusMap,
      stockOutStatusMap,
      useTypeMap,
      tables: {
        columns: [
          { lable: "VIN", key: "vin", width: "160px", align: "center" },
          {
            lable: "大区",
            key: "saleRegionName",
            width: "80px",
            align: "center",
          },
          { lable: "省份", key: "province", width: "80px", align: "center" },
          { lable: "城市", key: "city", width: "80px", align: "center" },
          {
            lable: "店简称",
            key: "dealerShortName",
            width: "100px",
            align: "center",
          },
          {
            lable: "店代码",
            key: "dealerCode",
            width: "80px",
            align: "center",
          },
          {
            lable: "店类型",
            key: "dealerType",
            width: "100px",
            align: "center",
          },
          {
            lable: "车系标准名称",
            key: "seriesNormalName",
            width: "160px",
            align: "center",
          },
          { lable: "车系", key: "seriesName", width: "120px", align: "center" },
          { lable: "车型", key: "modelName", width: "160px", align: "center" },
          { lable: "颜色", key: "colorName", width: "100px", align: "center" },
          {
            lable: "开票单位",
            key: "invoiceCompany",
            width: "160px",
            align: "center",
          },
          {
            lable: "是否本店开票",
            key: "localInvoicing",
            width: "100px",
            align: "center",
          },
          {
            lable: "开票价",
            key: "invoicingPrice",
            width: "80px",
            align: "center",
          },
          {
            lable: "开票城市",
            key: "invoiceAddress",
            width: "180px",
            align: "center",
          },
          {
            lable: "上牌人姓名",
            key: "plateName",
            width: "90px",
            align: "center",
          },
          { lable: "购车领域", key: "buyType", width: "80px", align: "center" },
          { lable: "使用性质", key: "useType", width: "80px", align: "center" },
          {
            lable: "上牌大区",
            key: "plateBigArea",
            width: "80px",
            align: "center",
          },
          {
            lable: "上牌省份",
            key: "plateProvince",
            width: "80px",
            align: "center",
          },
          {
            lable: "上牌城市",
            key: "plateCity",
            width: "80px",
            align: "center",
          },
          {
            lable: "上牌区县",
            key: "plateArea",
            width: "80px",
            align: "center",
          },
          {
            lable: "车牌号",
            key: "plateNumber",
            width: "100px",
            align: "center",
          },
          {
            lable: "发车日期",
            key: "deliveryDate",
            width: "90px",
            align: "center",
          },
          {
            lable: "入库日期",
            key: "stockInTime",
            width: "90px",
            align: "center",
          },
          {
            lable: "出库日期",
            key: "stockOutTime",
            width: "90px",
            align: "center",
          },
          {
            lable: "开票日期",
            key: "invoiceDate",
            width: "90px",
            align: "center",
          },
          {
            lable: "上牌日期",
            key: "plateDate",
            width: "150px",
            align: "center",
          },
        ],
        data: [],
      },
      pages: {
        pageNum: 1,
        pageSize: 20,
      },
      total: 0,
      listLoading: true,
      detailVisible: false,
      isMore: false,
      detailData: {},
      simpleForm: {},
      complexForm: {},
      invoiceDate: [],
      plateDate: [],
      // 大区数据
      regions: getStorageByKey("regionsMap"),
      // 上牌大区数据
      plateRegions: getStorageByKey("regionsMap"),
      // 车系车型数据集
      vehicleOptions: getStorageByKey("vehicleMap"),
      // 车系标准名称(去重)
      vehicleNormalOptions: unique_arr_by_key('seriesNormalName', getStorageByKey('vehicleMap'))
    };
  },
  computed: {
    // 省份下拉选项 跟随所选大区而变化
    provinceOptions() {
      if (this.regions && this.regions.length) {
        const currentBigArea = this.regions.filter(
          (item) => this.simpleForm.saleRegionName === item.bigAreaCode
        );
        const allProvince = this.regions.reduce((newArr, current) => {
          return newArr.concat(current.provinceList);
        }, []);
        if (currentBigArea.length)
          return unique_arr_by_key(
            "provinceCode",
            currentBigArea[0].provinceList
          );
        return unique_arr_by_key("provinceCode", allProvince);
      } else {
        return [];
      }
    },
    // 城市下拉选项 跟随所选省份而变化
    cityOptions() {
      const currentProvince = this.provinceOptions.filter(
        (item) => this.simpleForm.provinceCode === item.provinceCode
      );
      if (currentProvince.length) return currentProvince[0].cityDtoList;
      const allCity = this.provinceOptions.reduce((newArr, current) => {
        return newArr.concat(current.cityDtoList);
      }, []);
      return allCity;
    },
    // 上牌城市下拉选项 跟随上牌大区而变化
    plateCityOptions() {
      if (this.plateRegions && this.plateRegions.length) {
        // 获得所有城市列表
        const allCity = this.plateRegions.reduce((newArr, current) => {
          return newArr.concat(
            current.provinceList.reduce((newCityArr, currentProvince) => {
              return newCityArr.concat(currentProvince.cityDtoList);
            }, [])
          );
        }, []);
        // 获取所选大区下的城市
        const plateBigArea = this.complexForm.plateBigArea;
        const currentarea_next_province = this.plateRegions.filter(
          (item) => item.bigAreaCode === plateBigArea
        );
        console.log(currentarea_next_province);
        if (currentarea_next_province.length) {
          return currentarea_next_province[0].provinceList.reduce(
            (newArr, current) => {
              return newArr.concat(current.cityDtoList);
            },
            []
          );
        } else {
          return allCity;
        }
      } else {
        return [];
      }
      // return allCity
    },
    // 车型下拉选项，跟随车系而变化
    modelOptios() {
      if (this.vehicleOptions && this.vehicleOptions.length) {
        const { seriesName, seriesNormalName } = this.complexForm;
        const allModel = this.vehicleOptions.reduce((newArr, current) => {
          return unique_arr_by_key('modelName', newArr.concat(current.modelNameList))
        }, []);
        const currentModelList = this.vehicleOptions.filter(
          (item) =>
            item.seriesName === seriesName ||
            item.seriesNormalName === seriesNormalName
        );
        console.log(currentModelList);
        if (currentModelList.length) return currentModelList[0].modelNameList;
        return allModel;
      } else {
        return [];
      }
    },
  },
  created() {
    this.queryList();
  },
  methods: {
    // 分页
    changePages(params) {
      this.pages = { ...params };
      this.queryList();
    },
    async queryList() {
      this.formatParams();
      this.listLoading = true;
      const { data } = await queryList(this.formatParams());
      const items = data.data;
      this.tables.data = items.list;
      this.total = items.total;
      this.listLoading = false;
    },
    // 整理查询参数
    formatParams() {
      const params = { ...this.simpleForm, ...this.complexForm, ...this.pages };
      const { plateBigArea, plateCity } = this.complexForm;
      const saleRegionName = this.simpleForm.saleRegionName;
      // 将大区代码转换成对应名称
      if (saleRegionName) {
        const target = this.regions.find(
          (item) => item.bigAreaCode === saleRegionName
        );
        params["saleRegionName"] = target.bigAreaName;
      }
      // 将上牌大区代码转换成对应名称
      if (plateBigArea) {
        const target = this.regions.find(
          (item) => item.bigAreaCode === plateBigArea
        );
        params["plateBigArea"] = target.bigAreaName;
      }
      if (plateCity) {
        const target = this.cityOptions.find(
          (item) => item.cityCode === plateCity
        );
        params["plateCity"] = target.cityName;
      }
      if (this.invoiceDate && this.invoiceDate.length) {
        params["invoiceDateStart"] = dateFtt(this.invoiceDate[0]);
        params["invoiceDateEnd"] =
          dateFtt(this.invoiceDate[1], "yyyy-MM-dd") + " 23:59:59";
      }
      if (this.plateDate && this.plateDate.length) {
        params["plateDateStart"] = dateFtt(this.plateDate[0]);
        params["plateDateEnd"] =
          dateFtt(this.plateDate[1], "yyyy-MM-dd") + " 23:59:59";
      }
      return params;
    },
    // 清空查询条件
    handelRest() {
      for (const key in this.simpleForm) {
        this.simpleForm[key] = "";
      }
      this.clearComplexSearchCondetions();
    },
    // 清空复杂查询条件
    clearComplexSearchCondetions() {
      for (const key in this.complexForm) {
        this.complexForm[key] = "";
      }
      this.invoiceDate = [];
      this.plateDate = [];
    },
    // 切换高级搜索
    handelToggle() {
      this.isMore = !this.isMore;
      !this.isMore && this.clearComplexSearchCondetions();
    },
    // 查看详情
    handelCheckDetail(row) {
      this.detailVisible = true;
      this.detailData = row;
    },
    // 导出
    handelExport() {
      const params = this.formatParams();
      this.$delete(params, "pageNum");
      this.$delete(params, "pageSize");
      fenceVehicleExport(params).then((res) => {
        const { data } = res;
        console.log(res);
        console.log(data);
        const fileName = `${this.$route.meta.menuName}.xlsx`;
        exportExcelByBlob(data, fileName);
      });
    },
  },
};
</script>
<style lang="scss" scoped>
::v-deep(.el-form-item .el-form-item__content) {
  width: 200px;
}
.el-input {
  width: 202px;
}
.el-button--text {
  color: #02a8ac;
}
.detailContainer {
  display: flex;
  flex-wrap: wrap;
  padding: 0 15px;
  width: 100%;
  max-height: 400px;
  overflow-y: scroll;
  .detailItem {
    width: 33%;
    height: 50px;
    div {
      display: flex;
    }
    .detailTitle {
      font-weight: bold;
      display: inline-block;
      max-width: 120px;
      min-width: 60px;
    }
  }
}
.serach-container {
  width: 100%;
  display: flex;
  justify-content: space-between;
  .search-inputs {
    width: 90%;
  }
}
</style>
